<?php
namespace app\shop\service;
/**
 * 商品操作
 */
class ShopService extends \app\base\service\BaseService {

    private $model = 'shop/ShopOrder';

    /**
     * 添加购物车
     * @param $userId
     * @param $data
     * @return bool
     */
    public function addCart($userId, $data) {
        if(empty($data['pro_id']) || empty($data['qty'])) {
            return $this->error('商品参数有误!');
        }
        $proInfo = target('shop/ShopProducts')->getShopInfo($data['pro_id']);
        if(empty($proInfo) || !$proInfo['status']) {
            return $this->error('该商品不存在!');
        }
        if($proInfo['up_time']) {
            if($proInfo['up_time'] > time()) {
                return $this->error('该商品还未上架!');
            }
        }
        if($proInfo['down_time']) {
            if($proInfo['down_time'] < time()) {
                return $this->error('该商品已下架!');
            }
        }
        if(empty($proInfo['store'])) {
            return $this->error('该商品库存不足！');
        }

        if($proInfo['store'] < $data['qty']) {
            return $this->error('该商品库存不足!');
        }
        $cartData = [];
        $cartData['item_no'] = $proInfo['products_no'];
        $cartData['app'] = 'shop';
        $cartData['id'] = $proInfo['products_id'];
        $cartData['qty'] = $data['qty'];
        $cartData['price'] = $proInfo['sell_price'];
        $cartData['name'] = $proInfo['title'];
        $cartData['options'] = $proInfo['spec_data'];
        $cartData['shop_id'] = $proInfo['shop_id'];
        $cartData['image'] = $proInfo['image'];
        $cartData['weight'] = $proInfo['weight'];
        $cartData['point'] = $proInfo['point'];
        $cartData['url'] = url('shop/info/index', ['id' => $proInfo['shop_id']]);
        $cartData['comment_status'] = 0;
        $cartData['delivery_type'] = 1;  //需要物流
        $cartData['pay_type'] = 1; //付款方式
        if(!target('order/Cart', 'service')->add($userId, $cartData)) {
            return $this->error(target('order/Cart', 'service')->getError());
        }
        return $this->success();
    }

    /**
     * 添加收藏
     * @param $userId
     * @param $data
     * @return bool
     */
    public function addFollow($userId, $data) {
        if(empty($data['shop_id'])) {
            return $this->error('商品参数有误!');
        }
        $followInfo = target('shop/ShopFollow')->getWhereInfo(['app' => 'shop', 'has_id' => $data['shop_id']]);
        if(!empty($followInfo)) {
            if(!target('shop/Shop')->where(['shop_id' => $data['shop_id']])->setDec('favorite', 1)) {
                return $this->error('取消收藏失败！');
            }
            if(!target('shop/ShopFollow')->where(['app' => 'shop', 'has_id' => $data['shop_id']])->delete()) {
                return $this->error('取消收藏失败！');
            }else {
                return $this->success('商品已取消收藏！');
            }
        }
        $shopInfo = target('shop/Shop')->getInfo($data['shop_id']);
        if(empty($shopInfo) || !$shopInfo['status']) {
            return $this->error('该商品不存在!');
        }
        if($shopInfo['up_time']) {
            if($shopInfo['up_time'] > time()) {
                return $this->error('该商品还未上架!');
            }
        }
        if($shopInfo['down_time']) {
            if($shopInfo['down_time'] < time()) {
                return $this->error('该商品已下架!');
            }
        }

        if(!target('shop/Shop')->where(['shop_id' => $data['shop_id']])->setInc('favorite', 1)) {
            return $this->error('取消收藏失败！');
        }

        $data = [];
        $data['user_id'] = $userId;
        $data['app'] = 'shop';
        $data['has_id'] = $shopInfo['shop_id'];
        $data['time'] = time();
        $data['title'] = $shopInfo['title'];
        $data['image'] = $shopInfo['image'];
        $data['price'] = $shopInfo['sell_price'];
        if(!target('shop/ShopFollow')->add($data)) {
            return $this->error('收藏商品失败！');
        }

        return $this->success('商品收藏成功!');
    }

    /**
     * 刷新购物车
     * @param $userId
     * @param $data
     * @return bool
     */
    public function refreshCart($userId, $data) {
        if(empty($data)) {
            return $this->success();
        }
        $ids = [];
        foreach($data as $key => $vo) {
            $ids[] = $vo['id'];
        }
        $where = [];
        $where['_sql'] = 'products_id in (' . implode(',', $ids) . ')';
        $proList = target('shop/ShopProducts')->loadList($where);
        if(empty($proList)) {
            return $this->error('部分商品已过期!');
        }
        $proData = [];
        foreach($proList as $vo) {
            $proData[$vo['products_id']] = $vo;
        }
        $storeError = 0;
        $priceError = 0;
        $cartData = [];
        foreach($data as $key => $vo) {
            $cart = [];
            if($vo['qty'] > $proData[$vo['id']]['store']) {
                $storeError = 1;
                $cart['qty'] = 1;
            }
            if($vo['price'] <> $proData[$vo['id']]['sell_price']) {
                $priceError = 1;
                $cart['price'] = $proData[$vo['id']]['sell_price  '];
            }
            if($cart) {
                $cart['rowid'] = $key;
                $cartData[] = $cart;
            }
        }
        if(!empty($cartData)) {
            if(!target('order/Cart', 'service')->update($userId, $cartData)) {
                return $this->error(target('order/Cart', 'service')->getError());
            }
            if($storeError && $priceError) {
                return $this->error('您购买的产品由于库存和价格更改,请重新提交订单!');
            }
            if($storeError) {
                return $this->error('您购买的产品由于库存不足,请重新提交订单!');
            }
            if($priceError) {
                return $this->error('您购买的产品由于价格更改,请重新提交订单!');
            }
        }
        return $this->success();
    }

    /**
     * 提交订单
     * @param $userId
     * @param array $data
     * @param array $address
     * @param int $groupId
     * @return bool
     */
    public function addOrder($userId, $data = [], $address = [], $groupId = 0) {
        if(empty($data)) {
            return $this->error('提交商品不存在!');
        }
        if(empty($address)) {
            return $this->error('提交地址不存在!');
        }
        if(empty($groupId)) {
            return $this->error('分组订单号不存在!');
        }
        $ids = [];
        foreach($data as $key => $vo) {
            $ids[] = $vo['id'];
        }

        $priceTotal = 0;
        $countTotal = 0;

        foreach($data as $key => $vo) {
            $priceTotal += $vo['total'];
            $countTotal += $vo['qty'];
        }

        $curPro = reset($data);

        $orderData = [];
        $orderData['order_user_id'] = $userId;
        $orderData['order_app'] = 'shop';

        $orderData['order_title'] = $curPro['name'] . '等' . $countTotal . '件商品';
        $orderData['order_image'] = $curPro['image'];
        $orderData['order_price'] = $priceTotal;
        $orderData['order_sum'] = $countTotal;
        $orderData['order_items'] = serialize($data);
        $orderData['delivery_price'] = 0;
        $orderData['pay_type'] = 1;
        $orderData['delivery_type'] = 1;

        $orderData['receive_name'] = $address['receive_name'];
        $orderData['receive_tel'] = $address['receive_tel'];
        $orderData['receive_province'] = $address['receive_province'];
        $orderData['receive_city'] = $address['receive_city'];
        $orderData['receive_region'] = $address['receive_region'];
        $orderData['receive_address'] = $address['receive_address'];
        $orderData['receive_zip'] = $address['receive_zip'];

        $orderData['group_id'] = $groupId;

        $orderId = target('order/Order', 'service')->addItem($userId, $orderData);
        if(!$orderId) {
            return $this->error(target('order/Order', 'service')->getError());
        }
        $id = target($this->model)->add([
            'order_id' => $orderId
        ]);
        if(!$id) {
            return $this->error(target($this->model)->getError());
        }
        return $this->success($id);
    }

    /**
     * 支付检查
     * @param $orderRows
     * @return bool
     */
    public function checkPay($orderRows) {
        return false;
    }
}

